/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.transport.threadpool;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import cgl.narada.transport.TransportDebugFlags;
import cgl.narada.transport.TransportException;

/**
   Responsible for sending niotcp packets across the socket connection that is
   established during initializations. The PoolTCPSenderThread notifies any loss
   of connections to the PoolTCPLink which in turn proceeds to noitify the 
   PoolTCPLinkFactory. 
   
   @author Shrideep Pallickara
   $Revision$
   $Date$
*/

public class PoolTCPLinkSender implements TransportDebugFlags {
  private SocketChannel sc;
  
  private PoolTCPLink niotcpLink;
  private int packetTracker=0;
  private int lastPacketAcked =0;
  private int bufferTracker = 1;
  private int lastBuffer = 0;

  private String moduleName = "PoolTCPLinkSender: ";
  
  private ByteBuffer buffer;
  private int BUFFER_SIZE = 8192;
  private int tracker=0;
  private int bytesReleased = 0;

  private boolean sleeping = true;

  private int pending =0;
  private int intraPacketCount = 0;

  public PoolTCPLinkSender(SocketChannel sc, PoolTCPLink niotcpLink) 
    throws Exception{
    this.sc = sc;
    this.niotcpLink = niotcpLink;
    sc.configureBlocking(false);
    buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
  }
  
  public void releaseResources() {
    if (PoolTCPLinkSender_Debug)
      System.out.println(moduleName + "Closing " + sc );
    try {
      sc.close();
    } catch (IOException ioe) {
      System.out.println(moduleName + "Problem while releasing resources" +
			 ioe);
    }
  }
  
  public synchronized void sendData(byte[] dataToSend) 
    throws TransportException {
    if (PoolTCPLinkSender_Debug) {
      System.out.println(moduleName + "Sending ..." + dataToSend.length);
    }
    populateSendBuffers(dataToSend);
  }
  
  public void prepareToSendData(ByteBuffer readyToSend) throws Exception {
    int _willSend = readyToSend.remaining();
    int _actuallySent = 0;

    while (readyToSend.hasRemaining()) {
      _actuallySent += sc.write(readyToSend);
    }

    intraPacketCount += _willSend;
    bytesReleased += _willSend;
    
    if (_willSend != BUFFER_SIZE) {
      if (PoolTCPLinkSender_Debug) {
	System.out.println(moduleName + "IntraPacket count of sent stuff = [" +
			   intraPacketCount + "]");
      }
      intraPacketCount = 0;
    }
    
  }

  public void populateSendBuffers(byte[] dataToSend) 
    throws TransportException {
    int dataLength = dataToSend.length;
    try {
      if (dataLength <= 0) {
	System.out.println("\n **Sender: Data length <= 0 *** \n");
	return;
      }
      packetTracker++;

      int toBeSent = dataToSend.length + 4 /** for length */;
      if (toBeSent <= BUFFER_SIZE) {
	buffer.clear();
	buffer.putInt(dataLength);
	buffer.put(dataToSend);
	buffer.flip();
	prepareToSendData(buffer);
      } else {
	buffer.clear();
	buffer.putInt(dataLength);
	int canSend = BUFFER_SIZE -4;
	buffer.put(dataToSend, 0, canSend);
	buffer.flip();
	prepareToSendData(buffer);
	sendBuffer(dataToSend, canSend);
	if (PoolTCPLinkSender_Debug) {
	  System.out.println(moduleName + "Done sending " + dataToSend.length);
	}

      }
      tracker += toBeSent;
      if (PoolTCPLinkSender_Debug) {
	System.out.println(moduleName + "Bytes SENT so far= " 
			   + tracker + "\n");
      }
    } catch (Exception ioe) {
      String errorInfo = moduleName + "sending data " + ioe;
      System.out.println(errorInfo);
      throw new TransportException(errorInfo);
    }
  }

  private void sendBuffer(byte[] dataToSend, int sentSoFar) 
    throws TransportException {
    if (PoolTCPLinkSender_Debug) {
      System.out.println("sentSoFar=" + sentSoFar + " out of " + 
			 dataToSend.length);
    }
    try {
      int toSend = dataToSend.length - sentSoFar;
      if (toSend > BUFFER_SIZE) {
	buffer.clear();
	buffer.put(dataToSend, sentSoFar, BUFFER_SIZE);
	buffer.flip();
	prepareToSendData(buffer);
	sentSoFar += BUFFER_SIZE;
	sendBuffer(dataToSend, sentSoFar);
      } else {
	buffer.clear();
	buffer.put(dataToSend, sentSoFar, toSend);
	sentSoFar += toSend;
	buffer.flip();
	prepareToSendData(buffer);
	if (PoolTCPLinkSender_Debug) { 
	  System.out.println("sentSoFar=" + sentSoFar + " out of " + 
			     dataToSend.length);
	}
      }
    } catch (Exception ioe) {
      String errorInfo = moduleName + "sending data " + ioe;
      System.out.println(errorInfo);
      throw new TransportException(errorInfo);
    }/* end try-catch */
  }
  
  
  public void sendData(byte[] dataToSend, 
		       String dataType) throws TransportException {
    /** NBNI*/
    sendData(dataToSend);
  }

}
